// 包含各种API接口定义的JavaScript文件

// RESTful API配置
const REST_API = {
    baseURL: "https://api.example.com/rest/v1",
    endpoints: {
        users: "/rest/v1/users",
        posts: "/rest/v1/posts",
        comments: "/rest/v1/comments",
        files: "/rest/v1/files"
    },
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
    }
};

// GraphQL API配置
const GRAPHQL_CONFIG = {
    endpoint: "https://api.example.com/graphql",
    wsEndpoint: "ws://api.example.com/graphql",
    queries: {
        getUser: `
            query GetUser($id: ID!) {
                user(id: $id) {
                    id
                    name
                    email
                    posts {
                        id
                        title
                    }
                }
            }
        `,
        getPosts: `
            query GetPosts($limit: Int!) {
                posts(limit: $limit) {
                    id
                    title
                    content
                    author {
                        name
                    }
                }
            }
        `
    }
};

// 微服务API列表
const MICROSERVICES = {
    auth: {
        base: "http://auth-service:8080",
        endpoints: {
            login: "/api/auth/login",
            logout: "/api/auth/logout",
            refresh: "/api/auth/refresh",
            validate: "/api/auth/validate"
        }
    },
    user: {
        base: "http://user-service:8081",
        endpoints: {
            profile: "/api/users/profile",
            update: "/api/users/update",
            delete: "/api/users/delete"
        }
    },
    file: {
        base: "http://file-service:8082",
        endpoints: {
            upload: "/api/files/upload",
            download: "/api/files/download",
            delete: "/api/files/delete"
        }
    }
};

// API调用函数
class APIService {
    constructor(baseURL) {
        this.baseURL = baseURL;
    }

    async get(endpoint) {
        const url = `${this.baseURL}${endpoint}`;
        return fetch(url, {
            method: 'GET',
            headers: REST_API.headers
        });
    }

    async post(endpoint, data) {
        const url = `${this.baseURL}${endpoint}`;
        return fetch(url, {
            method: 'POST',
            headers: REST_API.headers,
            body: JSON.stringify(data)
        });
    }

    async put(endpoint, data) {
        const url = `${this.baseURL}${endpoint}`;
        return fetch(url, {
            method: 'PUT',
            headers: REST_API.headers,
            body: JSON.stringify(data)
        });
    }

    async delete(endpoint) {
        const url = `${this.baseURL}${endpoint}`;
        return fetch(url, {
            method: 'DELETE',
            headers: REST_API.headers
        });
    }
}

// 具体API调用示例
const apiService = new APIService('https://api.example.com');

// 用户相关API
async function getUser(userId) {
    return apiService.get(`/api/v1/users/${userId}`);
}

async function createUser(userData) {
    return apiService.post('/api/v1/users', userData);
}

async function updateUser(userId, userData) {
    return apiService.put(`/api/v1/users/${userId}`, userData);
}

async function deleteUser(userId) {
    return apiService.delete(`/api/v1/users/${userId}`);
}

// 文件上传API
async function uploadFile(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    return fetch('/api/v2/upload', {
        method: 'POST',
        body: formData,
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
    });
}

// GraphQL查询
async function graphqlQuery(query, variables) {
    return fetch(GRAPHQL_CONFIG.endpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({ query, variables })
    });
}

// WebSocket连接
function connectWebSocket() {
    const ws = new WebSocket('ws://localhost:8080/api/v1/ws');
    
    ws.onopen = function() {
        console.log('WebSocket connected');
        ws.send(JSON.stringify({
            type: 'subscribe',
            channel: 'notifications'
        }));
    };
    
    ws.onmessage = function(event) {
        const data = JSON.parse(event.data);
        console.log('Received:', data);
    };
}

// 批量API调用
const API_BATCH = {
    users: {
        list: '/api/v1/users',
        detail: '/api/v1/users/{id}',
        create: '/api/v1/users',
        update: '/api/v1/users/{id}',
        delete: '/api/v1/users/{id}'
    },
    posts: {
        list: '/api/v1/posts',
        detail: '/api/v1/posts/{id}',
        create: '/api/v1/posts',
        update: '/api/v1/posts/{id}',
        delete: '/api/v1/posts/{id}'
    },
    comments: {
        list: '/api/v1/comments',
        detail: '/api/v1/comments/{id}',
        create: '/api/v1/comments',
        update: '/api/v1/comments/{id}',
        delete: '/api/v1/comments/{id}'
    }
};

// 动态API路径构建
function buildAPIPath(base, resource, id = null) {
    let path = `${base}/api/v1/${resource}`;
    if (id) {
        path += `/${id}`;
    }
    return path;
}

// 使用示例
const endpoints = {
    // REST API
    GET: [
        buildAPIPath('https://api.example.com', 'users'),
        buildAPIPath('https://api.example.com', 'users', 123),
        '/api/v1/posts?limit=10&offset=0',
        '/api/v1/comments?post_id=456',
        '/rest/v1/search?q=test'
    ],
    POST: [
        '/api/v1/users',
        '/api/v1/posts',
        '/api/v1/auth/login',
        '/api/v2/upload'
    ],
    PUT: [
        '/api/v1/users/123',
        '/api/v1/posts/456',
        '/api/v1/comments/789'
    ],
    DELETE: [
        '/api/v1/users/123',
        '/api/v1/posts/456',
        '/api/v1/comments/789'
    ]
};

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        REST_API,
        GRAPHQL_CONFIG,
        MICROSERVICES,
        APIService,
        endpoints
    };
}
